"""
    create by IAmFiveHigh on 2024/5/23
"""
from LA.Matrix import Matrix
from LA.GramSchmidtProcess import gram_schmidt_process


def qr(matrix: 'Matrix') -> ('Matrix', 'Matrix'):
    assert matrix.row_num() == matrix.col_num(), "Error: qr分解的矩阵必须是方阵"

    basis = [matrix.col_vector(i) for i in range(matrix.col_num())]
    # 施密特正交化获得正交基
    res = gram_schmidt_process(basis)
    # 向量除以向量的模获得标准正交基
    res = [row / row.norm() for row in res]
    Q = Matrix(res).T()
    # 因为A = QR
    # 所以R = (Q的逆)·A ||  Q的逆 == Q的转置
    R = Q.T().dot(matrix)
    return Q, R
